<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="q">
          <el-form-item label="文章分类">
            <el-select v-model="q.cate_id" placeholder="请选择分类" size="small">
              <el-option v-for="item in cateList" 
              :key="item.id"
              :label="item.cate_name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px;">
            <el-select v-model="q.state" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="getArticleList()">筛选</el-button>
            <el-button type="info" size="small" @click="resetArticle">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button @click="showDialog=true" type="primary" size="small" class="btn-pub">发表文章</el-button>
      </div>

      <!-- 文章表格区域 -->
    <el-table
      border
      :data="articleList"
      style="width: 100%">
      <el-table-column
        label="文章标题"
        width="180">
          <template #default="{row}">
            <el-link @click="getArDetail(row.id)" type="primary">
              {{row.title}}
            </el-link>
          </template>
      </el-table-column>
      <el-table-column
        prop="cate_name"
        label="文章分类"
        width="180">
      </el-table-column>
      <el-table-column
        label="发布时间">
        <template #default="{row}">
          {{formatDate(row.pub_date)}}
        </template>
      </el-table-column>
      <el-table-column
        prop="state"
        label="发布状态">
      </el-table-column>
      <el-table-column
        label="操作">
        <template #default={row}>
        <el-button @click="delArticle(row.id)"
        type="danger" size="mini">删除
        </el-button>
        </template>
      </el-table-column>
    </el-table>

      <!-- 分页区域 -->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="q.pagenum"
        :page-sizes="[5,10,20,50,100]"
        :page-size="q.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>
    </el-card>

     <!-- 发表对话框 -->
    <el-dialog title="发布文章" 
    @close="resetPubForm"
    :before-close="handleClose"
    :visible.sync='showDialog' fullscreen>
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="文章标题" prop="title">
            <el-input v-model="ruleForm.title" ></el-input>
        </el-form-item>
        <el-form-item label="文章分类" prop="cate_id">
            <el-select v-model="ruleForm.cate_id" placeholder="请选择活动区域" style="width:100%">
                    <el-option  v-for="item in cateList" :key="item.id"
                    :label="item.cate_name" :value="item.id"></el-option>
                </el-select>
            </el-form-item>
        <el-form-item label="文章内容" prop="content">
             <quill-editor v-model="ruleForm.content"></quill-editor>
        </el-form-item>
        <!-- 封面 -->
        <el-form-item label="文章封面">
            <!-- 用来显示封面的图片 -->
            <img src="../../../assets/images/cover.jpg" alt="" class="cover-img" ref="imgRef" />
            <br />
            <!-- 文件选择框，默认被隐藏 -->
            <input @change='chooseImg' type="file" style="display: none;" accept="image/*" ref="iptFile" />
            <!-- 选择封面的按钮 -->
            <el-button @click="$refs.iptFile.click()" type="text">+ 选择封面</el-button>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="pubArticle('已发布')">发布</el-button>
                <el-button type="info" @click="pubArticle('草稿')">存为草稿</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
    <!-- 显示文章详情的对话框 -->
    <el-dialog title="文章详情" :visible.sync="showDeailDialog" width="80%">
      <h1 class="title">{{artDetail.title}}</h1>
      <div class="info">
          <span>作者：{{ artDetail.nickname || artDetail.username }}</span>
          <span>发布时间：{{ formatDate(artDetail.pub_date) }}</span>
          <span>所属分类：{{ artDetail.cate_name }}</span>
          <span>状态：{{ artDetail.state }}</span>
        </div>
        
        <!-- 分割线 -->
        <el-divider></el-divider>

        <img :src="'http://big-event-vue-api-t.itheima.net' + artDetail.cover_img" alt="" />

        <div v-html="artDetail.content"></div>
    </el-dialog>
  </div>
</template>

<script>
import defaultImg from '@/assets/images/cover.jpg'
import  dayjs from 'dayjs' 
//dayjs(需要格式化的时间).format(格式化的时间):返回值是格式化好的事件
export default {
    name: "ArtList",
data() {
    return {
        showDeailDialog:false,  //控制弹层的显示和隐藏
        // currentPage4: 1, //跳转第几页
        articleList:[], //保存文章列表
        cateList:[], //保存文章
        showDialog: false, //控制发布文章的对话框的显示和隐藏
        ruleForm:{
            title:'',
            cate_id:'',
            content:'',
            cover_img:null, //储存文件对象
            state:'草稿'  //存储文章状态  已发布||草稿
        },
        rules:{
            title:[
                {required:true,message:'请输入文章标题',trigger:'blur'},
                {min:1,max:30,message:'请输入长度1~30的文章标题',trigger:'blur'}
            ],
            cate_id:[
                {required:true,message:'请选择文章分类',trigger:['blur','change']}
            ],
            content:[
                {required:true,message:'请选择文章内容',trigger:'blur'}
            ]
        },
        // 查询参数对象
        q: {
            pagenum: 1,   //当前页码值
            pagesize: 5, //默认每页要显示的条数
            cate_id: "",
            state: "",
        },
        total:0, //保存文章的总数
        artDetail:{} //保存文章详情的数据
    };
},
    created(){
        this.getArtCateList()   //获取文章分类
        this.getArticleList()   //获取文章列表
    },
    methods: {
        //发布文章退出提示
        handleClose() {
        this.$confirm("你确定关闭?")
            .then(() => {
            this.showDialog = false;
            })
            .catch((err) => console.log(err));
        },
        //获取文章分类数据
        async getArtCateList(){
            const {data:res} = await this.$http.get('/my/cate/list')
            console.log('res',res);
            this.cateList=res.data
        },
        chooseImg(e){
            const files = e.target.files
            if(files.length){
                //选择了图片
                this.ruleForm.cover_img=files[0]
                const url = URL.createObjectURL(files[0])
                
                console.log('url',url);
                this.$refs.imgRef.src=url
            }else {
                this.$refs.imgRef.src=defaultImg
                this.ruleForm.cover_img=null
            }
        },
        //发布文章
        pubArticle(state){
            this.ruleForm.state = state
            this.$refs.ruleForm.validate(async(valid)=>{
                if(!valid) return //校验失败
                if(this.ruleForm.cover_img===null) {
                    this.$message.error('请上传文章封面!')
                }
                const fd = new FormData()
                // fd.append('title',this.ruleForm.title)
                // fd.append('cate_id',this.ruleForm.cate_id)
                // fd.append('content',this.ruleForm.content)
                // fd.append('cover_img',this.ruleForm.cover_img)
                // fd.append('state',this.ruleForm.state)

                //优化
                Object.keys(this.ruleForm).forEach(key=>{
                  fd.append(key,this.ruleForm[key])
                })
                const {data:res} = await this.$http.post('/my/article/add',fd)
                if(res.code !== 0) return   //this.$message.error(res.message)
                this.$message.success(res.message)
                this.showDialog=false
                this.getArticleList()
            })
        },
        //重置发布文章表单
        resetPubForm(){
          this.$refs.ruleForm.resetFields()//重置表单
          this.ruleForm.cover_img=null
          this.$refs.imgRef.src = defaultImg
          this.ruleForm.state='草稿'
        },
        async getArticleList(){
          const {data:res} = await this.$http.get('/my/article/list',{params:this.q})
          console.log('getArticleList',res);
          if(res.code ===0){
            this.articleList=res.data
            this.total = res.total
          }
        },
        //使用dayjs进行事件的格式化
        formatDate(time){
          //使用dayjs进行事件的格式化
          return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
        },
        //分页
        handleSizeChange(val) {
          console.log(`每页 ${val} 条`);
          this.q.pagenum=1
          this.q.pagesize=val     
          this.getArticleList()
        },
        handleCurrentChange(val) {
          console.log(`当前页: ${val}`);
          this.q.pagenum=val     //改变请求参数pagenum值
          this.getArticleList()  //重新发送请求,重新获取数据
        },
        resetArticle(){
          this.q={
            pagenum: 1,   //当前页码值
            pagesize: 5, //默认每页要显示的条数
            cate_id: "",  //文章分类
            state: "",    //文章状态
          }
          this.getArticleList()
        },
        async getArDetail(id){
          const {data:res} = await this.$http.get('/my/article/info',{params:{id}})
          if(res.code === 0){
            this.artDetail =res.data
          }
          this.showDeailDialog=true
        },
        //删除
        delArticle(id){
          this.$confirm('你要删除该文章吗?').then(async()=>{
            const {data:res} = await this.$http.delete('/my/article/info',{params:{id}})
            if(res.code !==0) return this.$message.error(res.message) //删除失败
            this.$message.success(res.message) //删除成功
            //判断当前页面是否只剩下最后一条数据
            if(this.articleList.length === 1){
              this.q.pagenum--
            }
            this.getArticleList()
          }).catch(err=>{console.log(err)})
        }
      },  
};
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }
}
/deep/ .ql-editor {
  min-height: 300px;
}
.title {
  font-size: 24px;
  text-align: center;
  font-weight: normal;
  color: #000;
  margin: 0 0 10px 0;
}

.info {
  font-size: 12px;
  span {
    margin-right: 20px;
  }
}
</style>